<template>
  <view @touchmove.prevent.stop>
    <u-popup
      ref="loginPopup"
      type="bottom"
      :closeable="true"
      :round="10"
      @close="close"
      :show="show"
      :zIndex="199999"
    >
      <view class="uni-tip">
        <view class="infologo">
          <!-- <image :src="$util.img('image/logo.png')" mode="" lazy-load class="logo"></image> -->
          <image
            :src="$util.img('image/erqi/loginJoin.png')"
            mode=""
            lazy-load
            class="m-b-20"
            style="width: 190rpx; height: 28rpx"
          ></image>
          <text class="font-24" style="color: #151826">-登录享更多权益-</text>
        </view>
        <view style="height: 280rpx"></view>
        <block v-if="loginType == 'mobile'">
          <view class="row flex-between">
            <input
              type="number"
              placeholder="请输入手机号"
              placeholder-class="placeholder"
              class=""
              v-model="mobile"
            />
          </view>
          <view class="row flex-between">
            <input
              type="number"
              placeholder="请输入验证码"
              placeholder-class="placeholder"
              v-model="code"
              style="width: 200rpx"
            />
            <view class="code flex-y-center" @click="sendDynaCode">
              {{ codeText }}
            </view>
          </view>
        </block>

        <!-- <view class="uni-company flex-y-center">
          <image :src="$util.img('image/logo.png')" mode=""></image>
          润泽无忧家 申请
        </view>
        <view class="uni-shuo">
          <view class="font-size-toolbar">请设置头像、昵称</view>
          <view class="font-size-tag color-tip">方便平台及时为您服务</view>
        </view>
        <view class="avatarbox">
          <button
            class="avatar"
            open-type="chooseAvatar"
            @chooseavatar="onChooseAvatar"
            style="margin: 0; padding: 0"
          >
            <image
              :src="$util.img(avatarUrl.images)"
              mode=""
              v-if="avatarUrl.images"
            ></image>
            <image :src="$util.img('image/person.png')" mode="" v-else></image>
          </button>
          <view>上传头像
		  </view>
        </view>

        <view class="form-row">
          <view class="m-r-20">昵称
		  </view>
          <view class="" style="flex: 1">
            <input
              placeholder="请输入昵称"
              type="nickname"
              v-model="nickName"
            />
          </view>
        </view> -->
        <block v-if="loginType == 'weixin'">
          <button
            class="loginBtn"
            open-type="getPhoneNumber"
            @getphonenumber="getphonenumber"
            v-if="is_mobile == 0"
          >
            登录
          </button>
          <button class="loginBtn" @click="login" v-else>登录</button>
        </block>
        <block v-else>
          <button class="loginBtn" @click="mobileLogin()">登录</button>
        </block>

        <view
          class="flex-x-center font-26 color-title2 m-b-88"
          v-if="loginType == 'weixin'"
          @click="changeLoginType('mobile')"
        >
          <text>使用手机验证码登录</text>
        </view>
        <view
          class="flex-x-center font-26 color-title2 m-b-88"
          v-else
          @click="changeLoginType('weixin')"
        >
          <text>使用微信一键登录</text>
        </view>

        <view class="agree" @click="checked = !checked">
          <image
            :src="
              checked
                ? $util.img('image/radio2.png')
                : $util.img('image/radio.png')
            "
            mode=""
          ></image>
          请阅读<text class="color-title2" @click.stop="goTo(1)"
            >《用户协议》</text
          >
          <text class="color-title2" @click.stop="goTo(2)">《隐私政策》</text>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { mapState } from "vuex";
import config from "@/common/js/config.js";
export default {
  name: "login-pop",
  data() {
    return {
      avatarUrl: {
        images: "",
        path: "",
      },
      nickName: "",
      is_mobile: 0, //0未授权手机号，1已授权手机号
      show: false,
      checked: false,
      openid: "",
      loginType: "weixin", //mobile

      // 手机号登录
      mobile: "",
      code: "",
      codeKey: "",
      //验证码
      codeText: "获取验证码",
      seconds: 60,
      timer: null,
      isSend: false,
    };
  },
  watch: {
    seconds(value) {
      if (value == 0) {
        this.seconds = 60;
        this.codeText = "重新获取";
        this.isSend = false;
        clearInterval(this.timer);
      }
    },
  },
  created() {
    if (!uni.getStorageSync("token")) {
      this.getOpenId();
    }
  },
  methods: {
    changeLoginType(type) {
      this.loginType = type;
      this.mobile = "";
      this.codeKey = "";
      this.code = "";
    },
    mobileLogin() {
      // 增加手机号和验证码必填校验
      if (this.mobile === "") {
        this.$util.showToast({
          title: "请输入手机号",
        });
        return;
      }
      if (this.code === "") {
        this.$util.showToast({
          title: "请输入验证码",
        });
        return;
      }

      if (!this.checked) {
        this.$util.showToast({
          title: "请同意用户协议",
        });
        return;
      }

      let data = {
        mobile: this.mobile,
        key: this.codeKey,
        code: this.code,
        weapp_openid: this.openid,
      };

      if (uni.getStorageSync("invite_id"))
        data.source_member = uni.getStorageSync("invite_id");

      this.$api.sendRequest({
        url: "/api/login/mobile",
        data: data,
        success: (res) => {
          if (res.code == 0) {
            uni.setStorage({
              key: "token",
              data: res.data.token,
              success: () => {
                this.$store.commit("setToken", res.data.token);
                // 添加区域绑定逻辑
                this.bindUserRegion();
                if (uni.getStorageSync("coupon_id")) {
                  this.receiveGiftCoupon(uni.getStorageSync("coupon_id"));
                }
                this.close();
              },
            });
          } else {
            this.$util.showToast({
              title: res.message,
            });
          }
        },
        fail: () => {
          this.$util.showToast({
            title: "登录失败",
          });
        },
      });
    },
    // 发送动态验证码
    sendDynaCode() {
      if (this.mobile == "") {
        this.$util.showToast({
          title: "请输入手机号",
        });
        return;
      }
      if (this.mobile.length != 11) {
        this.$util.showToast({
          title: "手机号格式不正确",
        });
        return;
      }

      if (this.isSend) return;
      this.isSend = true;

      this.$api.sendRequest({
        url: "/api/login/mobileCode",
        method: "POST",
        data: {
          mobile: this.mobile,
        },
        success: (res) => {
          if (res.code == 0) {
            this.codeKey = res.data.key;
            if (this.seconds == 60 && this.timer == null) {
              this.timer = setInterval(() => {
                this.seconds--;
                this.codeText = "重新获取(" + this.seconds + "s)";
              }, 1000);
            }
          } else {
            this.isSend = false;
            this.$util.showToast({
              title: res.msg,
            });
          }
        },
        fail: (res) => {
          this.isSend = false;
        },
      });
    },
    //协议
    goTo(type) {
      this.$util.redirectTo("/pages/agree/agree?type=" + type);
    },
    open() {
      this.show = true;
    },
    close() {
      this.show = false;
    },
    // 上传头像
    onChooseAvatar(e) {
      console.log("888", e);
      const { avatarUrl } = e.detail;
      this.avatarUrl.path = avatarUrl;
      var that = this;

      // #ifdef MP-WEIXIN
      const app_type = "weapp";
      const app_type_name = "微信小程序";
      // #endif

      // #ifdef APP-PLUS
      const app_type = "app";
      const app_type_name = "APP";
      // #endif

      uni.uploadFile({
        url: config.baseUrl + "/api/upload/img",
        filePath: avatarUrl,
        name: "file",
        formData: {
          app_type,
          app_type_name,
        },
        success: function (res) {
          var path_str = JSON.parse(res.data);
          if (path_str.code >= 0) {
            that.avatarUrl.images = path_str.data.pic_path;
          } else {
            that.$util.showToast({
              title: "上传失败",
            });
          }
        },
      });
    },
    getOpenId() {
      var that = this;
      uni.login({
        provider: "weixin",
        timeout: 3000,
        success: (res) => {
          if (res.code) {
            this.$api.sendRequest({
              url: "/weapp/api/weapp/authcodetoopenid",
              data: {
                code: res.code,
              },
              success: (res) => {
                if (res.code == 0) {
                  this.openid = res.data.openid;
                  this.isExitUser(res.data.openid);
                }
              },
            });
          }
        },
        fail: () => {
          this.$util.showToast({
            title: "请求失败",
          });
          return;
        },
      });
    },
    //检测openid是否存在
    isExitUser(openid) {
      this.$api.sendRequest({
        url: "/api/login/auth",
        data: {
          weapp_openid: openid,
        },
        success: (res) => {
          if (res.code >= 0) {
            this.is_mobile = 1;
          } else {
            this.is_mobile = 0;
          }
          console.log("is_mobile", this.is_mobile);
        },
      });
    },
    //第一次授权手机号
    getphonenumber(e) {
      // if (!this.avatarUrl.path) {
      //   this.$util.showToast({
      //     title: '请授权头像'
      //   });
      //   return
      // }
      // if (!this.nickName) {
      //   this.$util.showToast({
      //     title: '请输入昵称'
      //   });
      //   return
      // }

      if (!this.checked) {
        this.$util.showToast({
          title: "请同意用户协议",
        });
        return;
      }

      if (e.detail.errMsg == "getPhoneNumber:ok") {
        this.getCode(e.detail);
      }
    },
    //非第一次登录
    login() {
      // if (!this.avatarUrl.path) {
      // 	this.$util.showToast({
      // 		title: '请授权头像'
      // 	});
      // 	return
      // }
      // if (!this.nickName) {
      // 	this.$util.showToast({
      // 		title: '请输入昵称'
      // 	});
      // 	return
      // }

      if (!this.checked) {
        this.$util.showToast({
          title: "请同意用户协议",
        });
        return;
      }

      var data = {
        headimg: this.avatarUrl.images,
        nickname: this.nickName,
        weapp_openid: this.openid,
      };

      this.nextLogin(data);
    },
    getCode(detail) {
      var data = {
        headimg: this.avatarUrl.images,
        nickname: this.nickName,
        iv: detail.iv,
        encryptedData: detail.encryptedData,
        weapp_openid: this.openid,
      };

      this.nextLogin(data);
    },
    nextLogin(data) {
      var url = "";
      if (this.is_mobile == 0) url = "/api/tripartite/mobileAuth";
      else url = "/api/login/auth";
      // console.log("data1111", data);
      if (this.is_mobile == 0) {
        //第一次授权增加绑定关系
        if (uni.getStorageSync("invite_id"))
          data.source_member = uni.getStorageSync("invite_id");
      }

      this.$api.sendRequest({
        url: url,
        data: data,
        success: (res) => {
          //  console.log("data2222", res);
          if (res.code == 0) {
            uni.setStorage({
              key: "token",
              data: res.data.token,
              success: () => {
                this.$store.commit("setToken", res.data.token);
                uni.removeStorageSync("invite_id");
                // 添加区域绑定逻辑
                this.bindUserRegion();
                if (uni.getStorageSync("coupon_id")) {
                  this.receiveGiftCoupon(uni.getStorageSync("coupon_id"));
                }
                this.close();
              },
            });
          } else {
            this.$util.showToast({
              title: res.message,
            });
          }
        },
        fail: () => {
          this.$util.showToast({
            title: "登录失败",
          });
        },
      });
    },
    // 绑定用户区域
    bindUserRegion() {
      if (uni.getStorageSync("userRegion")) return;
      if (!uni.getStorageSync("cityInfo")) return;
      if (!uni.getStorageSync("token")) return;
      this.$api.sendRequest({
        url: "/api/member/bindRegion",
        data: {
          region_id: uni.getStorageSync("cityInfo").id,
        },
        success: (res) => {
          if (res.code == 0) {
            console.log("绑定区域成功");
            uni.setStorageSync("userRegion", 1);
          }
        },
      });
    },
    // 领取转赠的优惠券
    receiveGiftCoupon(coupon_id) {
      this.$api.sendRequest({
        url: "/coupon/api/coupon/regift",
        data: {
          coupon_id: coupon_id,
        },
        success: (res) => {
          if (res.code == 0) {
            this.$util.showToast({ title: "领取成功" });
            uni.removeStorageSync("coupon_id");
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.uni-tip {
  width: 100%;
  background: #f7f7f7;
  box-sizing: border-box;
  border-radius: 20rpx 20rpx 0 0;
  overflow: hidden;
  height: initial;
  padding: 30rpx;

  .uni-company {
    image {
      width: 48rpx;
      height: 48rpx;
      border-radius: 50%;
      margin-right: 20rpx;
    }
  }

  .uni-shuo {
    margin: 30rpx 0 30rpx;
    padding-bottom: 20rpx;
  }

  .avatarbox {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    image {
      width: 119rpx;
      height: 119rpx;
      border-radius: 50%;
    }
  }

  .form-row {
    display: flex;
    align-items: center;
    height: 115rpx;
    background-color: #f7f7f7;
    border-radius: 20rpx;
    padding: 30rpx;
    width: 612rpx;
    box-sizing: border-box;
    margin: 60rpx auto 30rpx;
  }

  .loginBtn {
    width: 620rpx;
    height: 88rpx;
    line-height: 88rpx;
    font-size: $font-size-sub;
    text-align: center;
    color: #fff;
    background: $color-title2;
    border-radius: 60rpx;
    margin: 0 auto 40rpx;
  }
}

button {
  background-color: transparent;
}
.red {
  color: #ff4457;
  font-size: 28rpx;
}
.agree {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #8d93a5;
  // margin-bottom: 70rpx;
  image {
    width: 30rpx;
    height: 30rpx;
    margin-right: 10rpx;
  }
}

.infologo {
  position: absolute;
  top: 88rpx;
  left: 50%;
  margin-left: -87rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .logo {
    width: 194rpx;
    height: 194rpx;
    border-radius: 50%;
    margin-bottom: 30rpx;
  }
}

.row {
  background: #fff;
  height: 114rpx;
  width: 626rpx;
  box-sizing: border-box;
  margin: 0 auto 50rpx;
  border-radius: 20rpx;
  padding: 0 32rpx;

  input {
    height: 114rpx;
    line-height: 114rpx;
  }

  .placeholder {
    font-size: 28rpx;
    color: #b2b3b7;
  }

  .code {
    font-size: 24rpx;
    color: $color-title2;
    margin-left: auto;
  }
}
</style>
